//
//  HCHomeViewController.swift
//  Hweibome
//
//  Created by 何川 on 15/12/6.
//  Copyright © 2015年 hechuan. All rights reserved.
//

import UIKit
import SVProgressHUD
private let HCStatusCellIdentifier = "CELL"

class HCHomeViewController: HCVisitorTableViewController {

    var statusListViewModel:HCStatusListViewModel = HCStatusListViewModel()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        if !userLogin{
            visitorView?.setVisitorInfo(nil, message: nil)
            return
        }
      //  printLog(pullDownTipLabel)
        setupUI()
        loadData()
    }
    
    
    /**
     设置界面
     */
    private func setupUI(){
        navigationItem.leftBarButtonItem = UIBarButtonItem(imgName: "navigationbar_friendsearch", target: self, action: "friendsearch")
        navigationItem.rightBarButtonItem = UIBarButtonItem(imgName: "navigationbar_pop", target: self, action: "friendsearch")
        setupTableView()
    }
    
    private func setupTableView(){
        
        tableView.registerClass(HCStatusCell.self, forCellReuseIdentifier: HCStatusCellIdentifier)
        
        // 设置自动计算行高
        // 会根据 contentView 的底部的最大y值去设置成 行高
        tableView.rowHeight = UITableViewAutomaticDimension
        // 设置预估高度,以让tableView能滚动
        // 越接近真实行高越好
        tableView.estimatedRowHeight = 200
        tableView.separatorStyle = .None
        
        tableView.tableFooterView = pullUpView
        
//        let refreshControl = HCRefreshControl()
//        refreshControl.addTarget(self, action: "test:", forControlEvents: UIControlEvents.ValueChanged)
//        tableView.addSubview(refreshControl)
        
        //刷新空间监听方法
        hcRefreshControl.addTarget(self, action: "loadData", forControlEvents: UIControlEvents.ValueChanged)
        tableView.addSubview(hcRefreshControl)
        
    }
    
    func test(refreshControl:HCRefreshControl){
        printLog("刷新方法run")
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(5*NSEC_PER_SEC)), dispatch_get_main_queue()) { () -> Void in
            printLog("结束加载")
            refreshControl.endRefreshing()
        }
    }
    //下拉控
    private lazy var pullUpView:UIActivityIndicatorView = {
        let view = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.WhiteLarge)
        view.color = UIColor.redColor()
        view.sizeToFit()
        return view
    }()
    
     @objc private func friendsearch(){
        let vc = HCTempViewController()
        navigationController?.pushViewController(vc, animated: true)
    }
    //刷新控件定义
    private var hcRefreshControl: HCRefreshControl = HCRefreshControl()
    //底部提示label
    private lazy var pullDownTipLabel: UILabel = {
        let label = UILabel()
        label.backgroundColor = UIColor.orangeColor()
        label.textColor = UIColor.whiteColor()
        label.font = UIFont.systemFontOfSize(12)
        label.textAlignment = .Center
        //默认隐藏
        label.hidden = true
        var frame = label.frame
        frame.size = CGSizeMake(SCREENW,35)
        frame.origin.y = 64 - 35
        label.frame = frame
        return label
    }()
   
}

extension HCHomeViewController{
    
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return statusListViewModel.statusList?.count ?? 0
    }
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

        
        let cell = tableView.dequeueReusableCellWithIdentifier(HCStatusCellIdentifier,forIndexPath: indexPath) as! HCStatusCell
        cell.statusViewModel = statusListViewModel.statusList![indexPath.row]
        return cell
        
    }
    
    override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
//        if !pullUpView.isAnimating() && indexPath.row == statusListViewModel.statusList!.count -1
//        {
        if !pullUpView.isAnimating() && indexPath.row == statusListViewModel.statusList!.count - 1 {

            printLog("last one message")
            pullUpView.startAnimating()
            loadData()
        }
    
    }
    
    

    
  @objc  private func loadData(){
    
      statusListViewModel.loadData(pullUpView.isAnimating()) { (isSuccess,count) -> () in
       if isSuccess {
            self.tableView.reloadData()
            if !self.pullUpView.isAnimating() {
                self.showPullDownTips(count)
            }
            
        }else {
            SVProgressHUD.showErrorWithStatus("请求失败")
        }
        self.endLoad()
        }
    }
    
    private func endLoad() {
        pullUpView.stopAnimating()
        hcRefreshControl.endRefreshing()
    }
    
    private func showPullDownTips(count: Int) {
        if self.pullDownTipLabel.hidden == false {
            return
        }
        
        if self.pullDownTipLabel.superview == nil {
            if let navCtrl = self.navigationController {
                navCtrl.view.insertSubview(self.pullDownTipLabel, belowSubview: navCtrl.navigationBar)
            }
        }
        if count == 0 {
            self.pullDownTipLabel.text = "没有新的微博数据"
        }else {
            self.pullDownTipLabel.text = "加载了\(count)条数据"
        }
        pullDownTipLabel.hidden = false
        ///这段代码需要理解,因为2个闭包
        UIView.animateWithDuration(1, animations: { () -> Void in
            self.pullDownTipLabel.transform = CGAffineTransformMakeTranslation(0, self.pullDownTipLabel.frame.height)
            }) { (_) ->Void in
                
                UIView.animateKeyframesWithDuration(1, delay: 1, options: [], animations: { () -> Void in
                    self.pullDownTipLabel.transform = CGAffineTransformIdentity
                    }, completion: { (_) -> Void in
                        self.pullDownTipLabel.hidden = true
                })
        }
       
    }
}





